import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { getDeptTree, createDept, updateDept, deleteDepts, changeDeptStatus } from '@/api/system/dept'
import type { Dept, ExtendedDept, CreateDept, UpdateDept } from '@/types/api/system/dept'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'

export const useDeptStore = defineStore('dept', () => {
    // ------------ 国际化和工具引入 ------------
    const { t } = useI18n()

    // ------------ 加载状态 ------------
    const loading = ref(false)
    const submitLoading = ref(false)
    
    // ------------ 数据列表 ------------
    const deptList = ref<ExtendedDept[]>([])
    
    // ------------ 查询参数 ------------
    const queryParams = reactive({
        name: '',
        status: undefined as 0 | 1 | undefined
    })
    
    // ------------ 树形展开状态 ------------
    const expandedKeys = ref<string[]>([])
    const isExpandAll = ref(false)
    
    // ------------ 弹窗状态 ------------
    const modalVisible = ref(false)
    const formMode = ref<'add' | 'edit'>('add')
    const currentId = ref<string>('')

    // ------------ 表单状态 ------------
    const form = reactive<CreateDept>({
        name: '',
        parentId: null,
        leader: '',
        phone: '',
        email: '',
        orderNum: 0,
        status: 1
    })

    // ------------ 部门树数据 ------------
    const deptTreeData = ref<ExtendedDept[]>([])

    // ------------ 数据操作方法 ------------
    /**
     * 获取部门列表
     */
    const fetchDeptList = async () => {
        try {
            loading.value = true
            const { data } = await getDeptTree()
            if (data) {
                const processData = (items: Dept[]): ExtendedDept[] => {
                    return items.map(item => ({
                        ...item,
                        statusLoading: false,
                        children: item.children ? processData(item.children) : undefined
                    }))
                }
                deptList.value = processData(data)
            }
        } catch (error) {
            message.error(t('dept.fetchFailed'))
        } finally {
            loading.value = false
        }
    }

    /**
     * 切换部门状态
     */
    const changeDeptStatusAction = async (id: string, status: 0 | 1) => {
        try {
            const res = await changeDeptStatus(id, status)
            if (res.success) {
                message.success(t('common.statusChangeSuccess'))
                return true
            }
            message.error(res.message || t('common.statusChangeFailed'))
            return false
        } catch (error) {
            message.error(t('common.statusChangeFailed'))
            return false
        }
    }

    /**
     * 删除部门
     */
    const removeDept = async (id: string) => {
        try {
            const res = await deleteDepts([id])
            if (res.success) {
                message.success(t('common.deleteSuccess'))
                await fetchDeptList()
                return true
            }
            message.error(res.message || t('common.deleteFailed'))
            return false
        } catch (error) {
            message.error(t('common.deleteFailed'))
            return false
        }
    }

    /**
     * 提交表单
     */
    const submitForm = async () => {
        try {
            submitLoading.value = true
            let res

            const data = { ...form }
            if (data.parentId === null) {
                data.parentId = null
            }

            if (formMode.value === 'add') {
                res = await createDept(data)
            } else {
                const updateData: UpdateDept = {
                    ...data,
                    id: currentId.value
                }
                res = await updateDept(currentId.value, updateData)
            }

            if (res) {
                message.success(t(formMode.value === 'add' ? 'common.createSuccess' : 'common.updateSuccess'))
                modalVisible.value = false
                resetForm()
                await fetchDeptList()
            }
        } catch (error) {
            message.error(t('common.submitFailed'))
        } finally {
            submitLoading.value = false
        }
    }

    // ------------ 重置方法 ------------
    /**
     * 重置表单
     */
    const resetForm = () => {
        form.name = ''
        form.parentId = null
        form.leader = ''
        form.phone = ''
        form.email = ''
        form.orderNum = 0
        form.status = 1
        currentId.value = ''
    }

    return {
        // 加载状态
        loading,
        submitLoading,
        
        // 数据列表
        deptList,
        deptTreeData,
        
        // 展开状态
        expandedKeys,
        isExpandAll,
        
        // 弹窗状态
        modalVisible,
        
        // 查询参数
        queryParams,
        
        // 表单状态
        form,
        formMode,
        currentId,

        // 方法
        fetchDeptList,
        changeDeptStatusAction,
        removeDept,
        submitForm,
        resetForm
    }
}) 